import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/md5_sign.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _userNameController = TextEditingController(); //用户名
  final _userPwdController = TextEditingController(); //密码
  final _userPwdController2 = TextEditingController(); //密码
  final _userCodeController = TextEditingController(); //验证码
  final _userReferrerController = TextEditingController(); //邀请人
  // 响应空白处的焦点的Node
  BlankToolBarModel barModel = BlankToolBarModel();
  ScrollController scrollController = ScrollController();

  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;
  String user_auth_code_exist = ''; //	注册时邀请码是否必填，Y是N否
  String tip = '';

  @override
  Widget build(BuildContext context) {
    double kWindowstateHeight =
        MediaQueryData.fromWindow(window).padding.top; //状态栏
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        body: BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("images/bg_login.png"),
                    fit: BoxFit.cover,
                  ),
                ),
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                height: ScreenUtil.getInstance().setHeight(1334),
                child: SingleChildScrollView(
                    controller: scrollController,
                    child: Column(
                      children: <Widget>[
                        Container(
                            margin:
                                EdgeInsets.only(top: kWindowstateHeight * 3),
                            width: ScreenUtil.getInstance().setWidth(120),
                            height: ScreenUtil.getInstance().setWidth(120),
                            child: Image.asset('images/logo.png')),
                        Container(
                          margin: EdgeInsets.only(
                              top: ScreenUtil.getInstance().setWidth(28)),
                          child: Text(
                            '欢迎注册油然而省',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance().setSp(30),
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                        Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setWidth(28),
                                ScreenUtil.getInstance().setWidth(28),
                                ScreenUtil.getInstance().setWidth(28),
                                ScreenUtil.getInstance().setWidth(28)),
                            // child:
                            //  Card(
                            // elevation: kMargin10,

                            color: Colors.white,
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  createInputText(_userNameController,
                                      hint: '请输手机号',
                                      imgPath: 'images/icon_iphone.png',
                                      obscureText: false,
                                      type: TextInputType.phone),
                                  createBtnInputText(_userCodeController,
                                      hint: '请输入验证码',
                                      imgPath: 'images/icon_iphone.png',
                                      obscureText: false,
                                      type: TextInputType.phone),
                                  createInputText(_userPwdController,
                                      hint: '请输入密码',
                                      imgPath: 'images/icon_lock.png',
                                      obscureText: true,
                                      type: TextInputType.visiblePassword),
                                  createInputText(_userPwdController2,
                                      hint: '请再次输入密码',
                                      imgPath: 'images/icon_lock.png',
                                      obscureText: true,
                                      type: TextInputType.visiblePassword),
                                  createInputText(_userReferrerController,
                                      hint: '输入推荐人手机号或邀请码',
                                      imgPath: 'images/icon_lock.png',
                                      obscureText: false),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(20) *
                                            2,
                                        0.0,
                                        0,
                                        0.0),
                                    alignment: Alignment.centerLeft,
                                    child: Text(
                                      tip,
                                      style: TextStyle(color: Colors.red),
                                    ),
                                  ),
                                  new Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0.0,
                                          ScreenUtil.getInstance()
                                                  .setWidth(20) *
                                              2,
                                          0,
                                          0.0),
                                      width: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.8,
                                      child: new RaisedButton(
                                          color: Colors.blue,
                                          shape: StadiumBorder(),
                                          child: new Padding(
                                            padding: new EdgeInsets.all(10.0),
                                            child: new Text(
                                              '注册',
                                              style: new TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 16.0),
                                            ),
                                          ),
                                          onPressed: () {
                                            requestRegister();
                                          })),
                                  new Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0.0,
                                          ScreenUtil.getInstance()
                                                  .setWidth(20) *
                                              2,
                                          0,
                                          0.0),
                                      width: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.8,
                                      child: new RaisedButton(
                                          color: Colors.blue,
                                          shape: StadiumBorder(),
                                          child: new Padding(
                                            padding: new EdgeInsets.all(10.0),
                                            child: new Text(
                                              '返回登录',
                                              style: new TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 16.0),
                                            ),
                                          ),
                                          onPressed: () {
                                            Navigator.pop(context, '');
                                          })),
                                ])
                            // )
                            ),
                      ],
                    )))));
  }

//图标 + 输���框
  Widget createInputText(TextEditingController controller,
      {obscureText: false, String hint, String imgPath, TextInputType type}) {
    FocusNode focusNode = barModel.getFocusNodeByController(controller);
    return Padding(
        padding: new EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(20) * 2,
            ScreenUtil.getInstance().setWidth(20) * 2,
            ScreenUtil.getInstance().setWidth(20) * 2,
            0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Image.asset(
                      imgPath,
                      fit: BoxFit.fill,
                    ),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750) * 0.6,
                    child: new TextField(
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText,
                        focusNode: focusNode),
                  ),
                  new IconButton(
                    icon: new Icon(Icons.clear, color: Colors.black45),
                    onPressed: () {
                      controller.clear();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

//图标 + 输入框+ 按钮
  Widget createBtnInputText(TextEditingController controller,
      {obscureText: false, String hint, String imgPath, TextInputType type}) {
    return Padding(
        padding: new EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(20) * 2,
            ScreenUtil.getInstance().setWidth(20),
            ScreenUtil.getInstance().setWidth(20) * 2,
            0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Image.asset(
                      imgPath,
                      fit: BoxFit.fill,
                    ),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750) * 0.43,
                    child: new TextField(
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText),
                  ),
                  new MaterialButton(
                    color: codeStatus == 1 ? Colors.blue : Colors.grey,
                    textColor: Colors.white,
                    child: new Text(
                      codeString,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                    ),
                    onPressed: () {
                      sendCode();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

  void _scrollTo() {
    //滑动到指定位置
    scrollController.jumpTo(100);
  }

  @override
  void initState() {
    super.initState();
    requestV();
    barModel.outSideCallback = focusNodeChange;
  }

  void focusNodeChange() {
    barModel.focusNodeListener();
    setState(() {});
  }

  // 保存账号密码
  void _saveLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("name", _userNameController.text);
    preferences.setString("pwd", _userPwdController.text);
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    barModel.removeFocusListeners();
    super.dispose();
  }

  requestV() async {
    Response<String> response =
        await HttpUtil().post(Api.GetVersionUrl, data: {});
    Map userMap = json.decode(response.data);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    print(userMap);
    if (code == 0) {
      if (mounted) {
        setState(() {
          if (userMap['data']['user_auth_code_exist'] == 'Y') {
            tip = '推荐人信息必填';
          } else {
            tip = '推荐人信息非必填';
          }
          user_auth_code_exist = userMap['data']['user_auth_code_exist'];
        });
      }
    }
  }

  sendCode() async {
    //发送短信验证码
    Map map = Map();
    map["phone"] = _userNameController.text;
    map['sign_type'] = 'yres.sms';
    // FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    // map['type'] = "mkyx.sms";
    // map = getSign(map);

    // FormData data = new FormData.fromMap({
    //   "phone": _userNameController.text,
    //   "timestamp": map['timestamp'],
    //   "data_type": map['data_type'],
    //   "version": map['version'],
    //   "sign": map['sign'],
    //   'type': map['type']
    // });
    Response<String> response =
        await HttpUtil().post(Api.SendUserRegisterUrl, data: getSign(map));
    Map userMap = json.decode(response.data);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

  requestRegister() async {
    //提交注册
    // print(_userNameController.text);
    // print(_userPwdController.text);
    if (user_auth_code_exist == 'Y') {
      if (_userReferrerController.text == '') {
        Toast.toast(context, msg: '请填写推荐人');
      }
    }
    if (_userNameController.text == '' ||
        _userPwdController.text == '' ||
        _userPwdController2.text == '' ||
        _userCodeController.text == '') {
      Toast.toast(context, msg: '请填写完整注册信息');
      return;
    }
    // FocusScope.of(context).requestFocus();
    FormData formData;
    if (_userReferrerController.text.length > 0) {
      if (_userReferrerController.text.length > 6) {
        formData = new FormData.fromMap({
          "phone": _userNameController.text,
          "code": _userCodeController.text,
          "pwd1": _userPwdController.text,
          "pwd2": _userPwdController2.text,
          "referrer_phone": _userReferrerController.text
        });
      } else {
        formData = new FormData.fromMap({
          "phone": _userNameController.text,
          "code": _userCodeController.text,
          "pwd1": _userPwdController.text,
          "pwd2": _userPwdController2.text,
          "auth_code": _userReferrerController.text
        });
      }
    } else {
      formData = new FormData.fromMap({
        "phone": _userNameController.text,
        "code": _userCodeController.text,
        "pwd1": _userPwdController.text,
        "pwd2": _userPwdController2.text
      });
    }
    print(formData);
    Response<String> response =
        await HttpUtil().post(Api.RegisterUrl, data: formData);
    Map userMap = json.decode(response.data);
    print(userMap);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      _saveLoginMsg();
      Navigator.pop(context, '');
    } else {}
  }
}
